
import scala.io.Source
import scala.util.matching._
import scala.util.matching.Regex._
import java.util.{Calendar, Date}

def getLinesFromFile(path: String) = new Iterator[String] {
  private val src = Source.fromFile(path)
  private val it = src.reset
  private val BOM = 0xfeff
  if (it.hasNext && it.next == BOM) src.next
  private val itr = src.getLines
  def hasNext: Boolean = itr.hasNext
  def next: String = itr.next.stripLineEnd
}

def getLinesFromStdin = new Iterator[String] {
  private var line = readLine
  def hasNext: Boolean = line != null
  def next: String = { val ret = line; line = readLine; ret } 
}

def getLinesFromFiles(files: Array[String]) = new Iterator[String] {
  private val itf = files.iterator
  private var itl = getLinesFromFile(itf.next)
  def hasNext: Boolean = {
    if (itl.hasNext) { true } else if (!itf.hasNext) { false } else {
      itl = getLinesFromFile(itf.next)
      hasNext
    }
  }
  def next: String = if (hasNext) itl.next else null
}

def puts(s: String) = println(s)

def ARGF = if (args.length > 0) getLinesFromFiles(args) else getLinesFromStdin

final class StringEx(self: String) {
  def =~(r: Regex): Boolean = {
    r.findFirstMatchIn(self) match {
      case Some(m) => true
      case None => false
    }
  }
  def gsub(p: String, s: String) = self.replaceAll(p, s)
}
implicit def string2StringEx(x: String) = new StringEx(x)

final class RegexEx(self: Regex) {
  def =~(s: String): Boolean = {
    self.findFirstMatchIn(s) match {
      case Some(m) => true
      case None => false
    }
  }
}
implicit def regex2RegexEx(x: Regex) = new RegexEx(x)

final class DateEx(self: Date) {
  def < (that: Date) = self.compareTo(that) < 0
  def <= (that: Date) = self.compareTo(that) <= 0
  def == (that: Date) = self.compareTo(that) == 0
  def > (that: Date) = self.compareTo(that) > 0
  def >= (that: Date) = self.compareTo(that) >= 0
}
implicit def date2DateEx(x: Date) = new DateEx(x)

final class CalendarEx(self: Calendar) {
  def < (that: Calendar) = self.compareTo(that) < 0
  def <= (that: Calendar) = self.compareTo(that) <= 0
  def == (that: Calendar) = self.compareTo(that) == 0
  def > (that: Calendar) = self.compareTo(that) > 0
  def >= (that: Calendar) = self.compareTo(that) >= 0
}
implicit def calendar2CalendarEx(x: Calendar) = new CalendarEx(x)
